<?php

namespace app\common\model;


use think\Paginator;

class OrderGoodsModel extends BaseModel
{
    protected $table='o_goods';

    const HANDLE_ACTION = 'action';
    const HANDLE_RUNNING = 'running';
    const HANDLE_CANCEL = 'cancel';
    const HANDLE_DETAIL = 'detail';

    protected $json = ['extra','logo_list'];



    protected $step_flow = [
        ['name'=>'退款流程','prop_func'=>'fields_is_back','field'=>'is_back'],
    ];



    public static function fields_is_back()
    {
        return [

        ];
    }

    //获取退款金额
    public function getProductBackMoneyAttr()
    {
        return $this['type']==3 ? 0 : $this['price'];
    }
    //售后列表
    public static function getSalesAfterList(array $input_data = [])
    {
        $activeState = $input_data['activeState']??'all';
        $limit = null;
        $where = [];

        if($activeState=='running'){
            $where[] = ['is_back','in',[1,2]];
        }elseif($activeState=='record'){
            $where[] = ['is_back','>',0];
        }

        $where[] = ['is_receive','=',1]; //已收货

        if(isset($input_data['uid'])){
            $where[] = ['uid', '=', $input_data['uid']];
        }

        if(isset($input_data['id'])){
            $where[] = ['id', '=', $input_data['id']];
        }else{
//            $where[] = ['receive_time','>',time()-OrderModel::ORDER_ORDER_BACK_TIME];
        }
//        dump($where);exit;

        return self::where($where)->paginate($limit);
    }



    //创建售后单
    public static function createSalesAfter(UserModel $user_model,array $input_data = [])
    {
        if(empty($input_data['id'])) throw new \Exception('参数异常:id');
        if(empty($input_data['type_intro'])) throw new \Exception('请选择退款类型');
        if(empty($input_data['reason_intro'])) throw new \Exception('请选择退款原因');
        if(empty($input_data['tel'])) throw new \Exception('请输入联系方式');
        if(empty($input_data['content'])) throw new \Exception('请输入退款理由');
        $model = self::where(['uid'=>$user_model['id'],'id'=>$input_data['id']])->find();
        if(empty($model)) throw new \Exception('订单产品信息异常');
        if(!empty($model['is_back'])) throw new \Exception('退款流程处理中,请耐心等待');

        if($model['uid']!=$user_model['id']) throw new \Exception('非本人订单，无法进行此操作');
        $order_model = OrderModel::find($model['oid']);
        if(empty($order_model)) throw new \Exception('系统未检测到订单信息');
//        if(!(in_array(self::HANDLE_ACTION,$model->getHandleAction('u_handle')) || in_array(OrderModel::ORDER_BACK_FORCE,$order_model->getHandleAction('u_handle'))))   throw new \Exception('订单未处于可退款状态,无法进行此操作');

        //创建退款记录
        try{
            \think\facade\Db::startTrans();
            $back_money = $model['type']==3 ? 0 : $model['price']*$model['num'];


            $order_model->setAttr('is_back',1);
            $order_model->setAttr('is_back_money',$back_money);
            $order_model->save();


            $row_num = self::where(['id'=>$model['id'],'is_back'=>$model['is_back']])->update([
                'back_no'=> self::getDateNo('90'),
                'back_money'=> $back_money,
                'is_back'=>1,
                'back_start_time'=>time(),
                'back_tel' => $input_data['tel'],
                'back_type_intro' => $input_data['type_intro'],
                'back_reason_intro' => $input_data['reason_intro'],

            ]);
            if(empty($row_num))   throw new \Exception('操作频繁...');

            //创建记录
//            $back_model = new OrderBackFollowModel();
//            $back_model->setAttrs([
//                'mch_id' => $order_model['mch_id'],
//                'uid' => $user_model['id'],
//                'cond_id' => $model['id'],
//                'tel' => $input_data['tel'],
//                'content' => $input_data['content'],
//                'img' => empty($input_data['img'])?'':(is_array($input_data['img'])?implode(',',$input_data['img']):$input_data['img']),
//            ]);
//            $back_model->save();

            \think\facade\Db::commit();
        }catch (\Exception $e){
            \think\facade\Db::rollback();
        }
    }


    /**
     * 待评价列表
     * @param array $input_data
     * @throws
     * @return \think\Paginator
     */
    public static function getWaitComment(array $input_data = [])
    {
        $is_comment = $input_data['is_comment']??0;
        $limit = $input_data['limit']??null;
        $where = [];
        if(isset($input_data['id'])){
            $where[] = ['id','=',$input_data['id']];
        }else{
            $where[] =['is_pay' ,'=', 1];
            $where[] =['is_comment' ,'=', $is_comment];
        }


        if(isset($input_data['uid'])){
            $where[] =['uid','=',$input_data['uid']];
        }
        return self::where($where)->order('id desc')->paginate($limit);
    }

    /**
     * 退款列表
     * @param array $input_data
     * @throws
     * @return \think\Paginator
     */
    public static function getBackData(array $input_data = [])
    {
        $limit = $input_data['limit']??null;
        $where = [];
        $where[] = ['is_back','>',0];
        if(isset($input_data['id'])){
            $where[] = ['id','=',$input_data['id']];
        }

        if(isset($input_data['uid'])){
            if(empty($input_data['uid'])){
                return Paginator::make(null,1,1,0);
            }
            $where[] =['uid','=',$input_data['uid']];

        }
        return self::where($where)->order('id desc')->paginate($limit);
    }

    public function apiCustomNormalInfo()
    {
        $linkOrder = $this->getRelation('linkOrder');

        return [
            'id'=> $this['id'],
            'order_no'=> (string)$this['order_no']??'',
            'num'=> (int)$this['num'],
            'name'=> (string)$this['name'],
            'price'=> (string)$this['price'],
            'total_money'=> number_format($this['price']*$this['num'],2),
            'create_time'=> empty($linkOrder)?null:$linkOrder['create_time'],
        ];
    }


    public static function backCancel(UserModel $user_model,array $input_data = [])
    {
        $id = $input_data['id']??0;
        if(empty($id)) throw new \Exception('参数异常:id');
        $model = self::where(['uid'=>$user_model['id'],'id'=>$id])->find();
        if(empty($model)) throw new \Exception('订单信息异常');

        $order_model = OrderModel::find($model['oid']);
        if(empty($order_model)) throw new \Exception('订单不存在');
//        $action = self::getPropInfo('fields_is_back',$model['is_back'],'action');
//        if(empty($action) || !in_array(self::HANDLE_CANCEL,$action))    throw new \Exception('未处于可取消状态,请返回重新操作');
        if(!in_array(self::HANDLE_CANCEL,$model->getHandleAction('u_handle')))   throw new \Exception('未处于可取消状态,请返回重新操作');
        $model->setAttrs([
            'step_flow'=>0,
            'is_back'=>0,
            'back_start_time'=>null,
            'back_handle_time'=>null,
            'back_end_time'=>null,
        ]);
        $model->save();

//        $back_follow = new OrderBackFollowModel();
//        $back_follow->setAttrs([
//            'uid' => $user_model['id'],
//            'cond_id' => $model['id'],
//            'content' => "用户取消退款流程",
//        ]);
//        $back_follow->save();
        //订单状态
        $order_model->setAttrs([
            'is_back' => 0,
        ]);
        $order_model->save();
        //申请记录
//        $model=$detail->linkBackFollow();
//        return $model;

    }


    public static function commentLists ( array $input_data = [] )
    {
        $activeState = $input_data['activeState']??'';
        $limit = $input_data['limit']??null;
        $where =[];

        if($activeState=='wait'){ //待评论
            $where[] = ['comment_state','=', 1];
        }elseif($activeState=='commented'){ //已评论
            $where[] = ['comment_state','=', 2];
        }

        if(isset($input_data['uid'])){
            $where[] = ['uid','=',$input_data['uid']];
        }
        return OrderGoodsModel::where($where)->paginate($limit);

    }



    public function apiFullInfo()
    {
        return array_merge($this->apiBackInfo(),[
            'comment_time' => (string)$this['comment_time'],
        ]);
    }

    public function apiBackInfo()
    {
//        $follow = $this->linkBackFollow;
        $follow_list = [];
        if(!empty($follow)){
            foreach ($follow as $vo){
                array_push($follow_list,$vo->apiNormalInfo());
            }
        }
        $back_info = self::getPropInfo('fields_is_back',$this['is_back']);
        return array_merge($this->apiNormalInfo(),[
            'back_no' => (string)$this['back_no'],
            'back_tel' => (string)$this->getAttr('back_tel'),
            'back_type_intro' => (string)$this->getAttr('back_type_intro'),
            'back_reason_intro' => (string)$this->getAttr('back_reason_intro'),
            'is_back' => (int)$this['is_back'],
            'is_back_name' => $back_info['name']??'',
            'back_start_time' => empty($this['back_start_time'])?'':date('Y-m-d H:i:s',$this['back_start_time']),
            'back_handle_time' => empty($this['back_handle_time'])?'':date('Y-m-d H:i:s',$this['back_handle_time']),
            'back_end_time' => empty($this['back_end_time'])?'':date('Y-m-d H:i:s',$this['back_end_time']),
            'back_money' => $this['back_money']??'0.00',
            'follow_list'=>$follow_list,
        ]);
    }


    public function apiNormalInfo()
    {
        return [
            'id' => $this->getAttr('id'),
            'type' => $this->getAttr('type'),
            'order_no' => (string)$this->getAttr('order_no'),
            'gno' => $this->getAttr('gno'),
            'gcode' => $this->getAttr('gcode'),
            'goods_id' => $this->getAttr('gid'),
            'sku_id' => $this->getAttr('sku_id'),
            'price' => $this->getAttr('price'),
            'num' => $this->getAttr('num'),
            'ser_minute' => $this->getAttr('ser_minute'),
            'price_minute' => $this->getAttr('price_minute'),
            'get_num' => $this->getAttr('get_num'),
            'award_num' =>$this->getAttr('award_num'),
            'total_price' => $this->getAttr('price')*$this->getAttr('num'),
            'name' => $this->getAttr('name'),
            'img' => $this->getAttr('img'),
            'sku_name' => (string)$this->getAttr('sku_name'),
            'intro' => (string)$this->getAttr('intro'),
            'logo' => (string)$this->getAttr('logo'),
            'logo_list' => $this->getAttr('logo_list'),
            'cond_color' => (string)$this->getAttr('cond_color'),
            'cond_name' => (string)$this->getAttr('cond_name'),
            'cond_remark' => (string)$this->getAttr('cond_remark'),

            'status_name' => '',//$this->getStepFlowInfo($this['step_flow']),
            'handle_action' => [],//$this->getHandleAction(app()->http->getName()==='admin'?'m_handle':'u_handle'),
        ];
    }

    public function linkOrder()
    {
        return $this->belongsTo(OrderModel::class, 'oid');
    }

//    public function linkBackFollow()
//    {
//        return $this->hasMany(OrderBackFollowModel::class, 'cond_id')->order('id desc');
//    }


}